package com.gyyweishang.filter;

import com.gyyweishang.utils.JwtUtils;
import com.gyyweishang.utils.CurrentHolder;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(urlPatterns = "/*")
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取请求路径
        String path = request.getRequestURI();
        //判断是否是登录请求，如果是，放行;路径中包含/login的都放行
        if (path.contains("/login")) {
            filterChain.doFilter(request, response);
            log.info("登录请求，放行");
            return;
        }
        //获取请求头中的令牌 token
        String token = request.getHeader("token");
        //判断令牌是否为空
        if (token == null || token.isEmpty()) {
            log.info("令牌为空，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //验证令牌是否正确
        try {
            Claims claims = JwtUtils.parseToken(token);//解析令牌
            Integer id = Integer.valueOf(claims.get("id").toString());
            CurrentHolder.setCurrentId(id);//当前用户ID存入当前线程局部变量中
            log.info("令牌正确，当前用户ID：{},将其存入ThreadLocal", id);

        } catch (Exception e) {
            log.info("令牌错误，响应401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //校验通过，放行
        log.info("令牌正确，放行");
        filterChain.doFilter(request, response);//放行，继续执行后续过滤器或者资源
        log.info("放行后。。");

        //放行执行后，删除当前线程ThreadLocal中的数据
        CurrentHolder.remove();

    }
}
